#define  _CRT_SECURE_NO_WARNINGS
#include"List.h"
LTNode* BuySListNode(DataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		perror("malloc:");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

LTNode* LTInit()
{
	LTNode* phead = BuySListNode(0);
	phead->prev = phead;
	phead->next = phead;
	return phead;
}

void LTPushBack(LTNode* phead, DataType x)
{
	assert(phead);
	/*LTNode* newnode = BuySListNode(x);
	LTNode* tail = phead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;*/


	LTInsert(phead,x);
}

void LTPrint(LTNode* phead)
{
	assert(phead);
	printf("phead");
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		printf("<=>%d", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void LTPopBack(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LTNode* tail = phead->prev;
	LTNode* tailpre = tail->prev;
	free(tail);
	tailpre->next = phead;
	phead->prev = tailpre;
}

void LTPushFront(LTNode* phead, DataType x)
{
	assert(phead);
	/*LTNode* newnode = BuySListNode(x);
	LTNode* pnext = phead->next;
	pnext->prev = newnode;
	newnode->next = pnext;
	newnode->prev = phead;
	phead->next=newnode;*/

	LTInsert(phead->next, x);
}

void LTPopFront(LTNode* phead)
{
	assert(phead);
	assert(phead->next != phead);
	LTNode* pnext = phead->next;
	phead->next = pnext->next;
	pnext->next->prev = phead;
	free(pnext);
}

int LTSize(LTNode* phead)
{
	assert(phead);
	int size = 0;
	LTNode* cur = phead;
	while (cur->next != phead)
	{
		size++;
		cur = cur->next;
	}
	return size;
}

LTNode* LTFind(LTNode* phead, DataType x)
{
	assert(phead);
	assert(phead->next != phead);
	LTNode* cur = phead;
	while (cur->next != phead)
	{
		cur = cur->next;
		if (x == cur->data)
		{
			return cur;
		}
	}
	return NULL;
}


void LTInsert(LTNode* pos, DataType x)
{
	assert(pos);
	LTNode* pospre = pos -> prev;
	LTNode* newnode = BuySListNode(x);
	pospre->next = newnode;
	newnode->prev = pospre;
	newnode->next = pos;
	pos->prev = newnode;
}

void LTErase(LTNode* pos)
{
	assert(pos);
	LTNode* pospre = pos->prev;
	LTNode* posnext = pos->next;
	pospre->next = posnext;
	posnext->prev = pospre;
	free(pos);
}